extends CharacterBody3D
class_name Knight

@export var rotation_speed = 12.0
@export var speed := 5.0 ##速度
@export var jump_speed := 8.0 ## 跳跃速度
@export var accelerationn = 4.0 ## 加速度
@export var mouse_sensitivity = 0.0015 ##鼠标灵敏度
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")
var jumping = false ## 是否处于跳跃状态
var last_floor = true

var attacks := [
	"1H_Melee_Attack_Slice_Horizontal",
	"1H_Melee_Attack_Chop",
	"1H_Melee_Attack_Slice_Diagonal"
]

@onready var spring_arm_3d: SpringArm3D = $SpringArm3D
@onready var model: Node3D = $Rig
@onready var anim_tree: AnimationTree = $AnimationTree
@onready var anim_state = $AnimationTree.get("parameters/playback")

func _physics_process(delta: float) -> void:
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
	velocity.y -= gravity * delta
	get_move_input(delta)

	move_and_slide()
	if velocity.length() > 1.0:
		model.rotation.y = lerp_angle(model.rotation.y, spring_arm_3d.rotation.y, rotation_speed * delta)
	if is_on_floor() and Input.is_action_just_pressed("jump"): # 起跳
		velocity.y =jump_speed
		jumping = true
		anim_tree.set("parameters/conditions/ground",false)
	anim_tree.set("parameters/conditions/jumping",jumping)	
		
	if is_on_floor() and not last_floor: #如果当前帧在地板,上一帧不在地板
		jumping = false
		anim_tree.set("parameters/conditions/ground",true)
	last_floor = is_on_floor()
	
	if not is_on_floor() and not jumping:
		anim_state.travel("Jump_Idle")
		anim_tree.set("parameters/conditions/ground",false) 

func get_move_input(delta:float) ->void:
	var vy = velocity.y
	velocity.y = 0
	var input = Input.get_vector("move_left","move_right","move_forward","move_backward")
	var dir = Vector3(input.x,0,input.y).rotated(Vector3.UP,spring_arm_3d.rotation.y)#角色将可以沿着相机所面向的方向的任何方向移动
	velocity = lerp(velocity,dir * speed,accelerationn * delta)
	var v1 = velocity * model.transform.basis##将全局速度矢量转到局部速度矢量,没提示的就是全局矢量
	anim_tree.set("parameters/IWR/blend_position",Vector2(v1.x,-v1.z)/speed)## -z是向前,但是+y代表向前.速度矢量除以最大速度得到[0,1]范围值
	
	velocity.y = vy
func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		spring_arm_3d.rotation.x -= event.relative.y * mouse_sensitivity
		spring_arm_3d.rotation_degrees.x = clamp(spring_arm_3d.rotation_degrees.x,-90.0,30.0)
		spring_arm_3d.rotation.y -= event.relative.x * mouse_sensitivity
		
	if event.is_action_pressed("attack"):
		anim_state.travel(attacks.pick_random())
